package com.musifind.activities;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.UserInfoChangedCallback;
import com.musifind.common.GeneralHelper;
import com.musifind.utils.AppUtil;
import com.musifind.utils.ImageUtils;
import com.musifind.utils.SessionManager;
import com.musifind.wsclient.objects.User;
import com.musifind.wsclient.service.UserService;

public class WelcomeActivity extends MusiFindFragmentActivity {

	private LoginButton btnLoginFacebook;
	private Button btnLoginEmail;
	private String userFullName, userFirstName, userLastName, userBirthday, userGender, userEmail; // facebook attributes
	private String profileId; // to get user's facebook page
	private Bitmap userPicture; // to get user's profile picture
	private UiLifecycleHelper uiHelper; // to handle the session
	HttpResponse response;
	ProgressDialog progressDialog = null;
	private SessionManager session;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_welcome);
		session = new SessionManager(getApplicationContext());

		uiHelper = new UiLifecycleHelper(this, statusCallback);
		uiHelper.onCreate(savedInstanceState);

		// Log.e("SESSION", Session.getActiveSession().isClosed() + " -- " + Session.getActiveSession().isOpened()
		// + " -- " + Session.getActiveSession().getState().toString());

		if (Session.getActiveSession().getState() == SessionState.CREATED_TOKEN_LOADED
				|| Session.getActiveSession().getState() == SessionState.OPENED) {
			progressDialog = new ProgressDialog(WelcomeActivity.this);
			progressDialog.setTitle("Bağlantı sağlanıyor");
			progressDialog.setMessage("Lütfen bekleyiniz...");
			progressDialog.setCancelable(false);
			progressDialog.show();
		}

		btnLoginEmail = (Button) findViewById(R.id.btnEmail);
		btnLoginEmail.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(WelcomeActivity.this, RegisterActivity.class);
				startActivity(i);
			}
		});

		btnLoginFacebook = (LoginButton) findViewById(R.id.btnFacebook);
		btnLoginFacebook.setBackgroundResource(R.drawable.transparent_themebutton_effect);
		btnLoginFacebook.setTextSize(18);
		btnLoginFacebook.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
		btnLoginFacebook.setUserInfoChangedCallback(new UserInfoChangedCallback() {
			@Override
			public void onUserInfoFetched(final GraphUser graphUser) {
				if (graphUser != null) {
					userFullName = graphUser.getName();
					userFirstName = graphUser.getFirstName();
					userLastName = graphUser.getLastName();
					userBirthday = graphUser.getBirthday();
					Object gender = graphUser.asMap().get("gender");
					if (gender != null)
						userGender = gender.toString();
					Object email = graphUser.getProperty("email");
					if (email != null)
						userEmail = email.toString();
					profileId = graphUser.getId();

					HttpClient client = new DefaultHttpClient();

					String strUserPicture = null;
					try {
						String urlProfilePicture = "http://graph.facebook.com/" + profileId
								+ "/picture?width=200&height=200";
						HttpGet get = new HttpGet(URI.create(urlProfilePicture));
						response = (HttpResponse) client.execute(get);
					} catch (ClientProtocolException e1) {
						e1.printStackTrace();
					} catch (IOException e1) {
						e1.printStackTrace();
					} finally {
						HttpEntity entity = response.getEntity();
						BufferedHttpEntity buf = null;
						try {
							buf = new BufferedHttpEntity(entity);
							InputStream inputStream = buf.getContent();
							userPicture = BitmapFactory.decodeStream(inputStream);
							Log.d("Facebook User Picture ", String.valueOf(userPicture));
							strUserPicture = GeneralHelper.bitmapToString(userPicture);
							Log.d("strUserPicture.length(); ", String.valueOf(strUserPicture.length()));
							session.setProperty(session.USER_PICTURE, strUserPicture);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					if (response != null) {
						new Thread(new Runnable() {
							@Override
							public void run() {
								try {
									synchronized (this) {
										wait(1);
									}
								} catch (InterruptedException e) {
									e.printStackTrace();
								} finally {
									finish();
									if (progressDialog != null)
										progressDialog.dismiss();
								}
								Intent intent = new Intent();
								intent.setClass(getApplicationContext(), HomepageActivity.class);
								startActivity(intent);
							}
						}).start();
					}

					// Kullanıcı oluştur veya bilgilerini güncelle
					if (!AppUtil.isDevelopment()) {
						User responseUser = UserService.getFaceUser(profileId);
						if (responseUser == null) {
							session.setProperty(session.IS_FACE_USER, true);
							session.setProperty(session.USERNAME, userFirstName);

							User user = new User();
							user.setAd(userFirstName);
							user.setSoyad(userLastName);
							user.setMail(userEmail);
							// FIXME : dogum tarihi string degil date olacak
							user.setDogumTarih(new Date());
							user.setCinsiyet(userGender);
							user.setFaceUser(true);
							user.setGcmRegId(session.getGCMRegistrationId());
							user.setFaceId(profileId);
							user.setImage(ImageUtils.getByteArray(userPicture));
							User response = UserService.createUser(user);
							session.createUserId(response.getId());
						} else {
							session.setProperty(session.IS_FACE_USER, true);
							session.setProperty(session.USERNAME, userFirstName);
							session.createUserId(responseUser.getId());
						}
					}

					Log.i("Facebook Values From GraphUser: ", "Full Name: " + userFullName + "\nFirst Name: "
							+ userFirstName + "\nLast Name: " + userLastName + "\nBirthday: " + userBirthday
							+ "\nGender: " + userGender + "\nE-mail: " + userEmail + "\nFB Profile ID: " + profileId);

				}
			}
		});

	}

	private Session.StatusCallback statusCallback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state, Exception exception) {
			if (state.isOpened()) {
				Log.d("Session onStatusCallback", String.valueOf(session));
				Log.d("Facebook", "Facebook session opened");
				Log.d("checkPermissions(): ", String.valueOf(checkPermissions()));
			} else if (state.isClosed()) {
				Log.d("Facebook", "Facebook session closed");
			}
		}
	};

	@Override
	public void onResume() {
		super.onResume();
		uiHelper.onResume();
	}

	@Override
	public void onPause() {
		super.onPause();
		uiHelper.onPause();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		uiHelper.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onSaveInstanceState(Bundle savedState) {
		super.onSaveInstanceState(savedState);
		uiHelper.onSaveInstanceState(savedState);
	}

}
